import { Location } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { STChange, STColumn, STComponent, STPage } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { NzFormatEmitEvent } from 'ng-zorro-antd/core/tree/public-api';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Api } from 'src/app/shared/api/api';
import { DELETED_STATUS_BADGE, RESOURCE_METHOD_ENUM, RESOURCE_METHOD_TAG } from 'src/app/shared/constant/common-constant';
import { ResponseCode } from 'src/app/shared/response.code';
import { PublicService } from 'src/app/shared/service/public.service';

@Component({
  selector: 'app-system-role-resource',
  templateUrl: './role-resource.component.html'
})
export class RoleResourceComponent implements OnInit {
  role: any = {};

  constructor(
    protected http: _HttpClient,
    public publicService: PublicService,
    private msg: NzMessageService,
    private location: Location,
    private route: ActivatedRoute
  ) {
    this.route.queryParams.subscribe((res: any) => {
      if (!res) {
        this.msg.error('参数有误');
        return;
      }
      this.role = res;
    });
  }
  params: any = {};
  page: any = {
    records: [],
    current: 1,
    total: 0,
    size: 10
  };
  pagination: STPage = {
    front: false,
    pageSizes: [10, 20, 30, 40, 50],
    total: true,
    showSize: true,
    showQuickJumper: true
  };
  searchSchema: SFSchema = {};
  @ViewChild('st', { static: true }) st!: STComponent;
  columns: STColumn[] = [
    { title: '序号', type: 'no', width: 60 },
    { title: '方法', index: 'method', type: 'tag', tag: RESOURCE_METHOD_TAG, width: 100 },
    { title: '资源', index: 'resource' },
    { title: '备注', index: 'remark' },
    { title: '状态', index: 'deleted', type: 'badge', badge: DELETED_STATUS_BADGE, width: 100 },
    { title: '是否授权', render: 'operation', width: 100 }
  ];
  selectedGroups: any[] = [];
  currentGroup: any = {};
  groupInfo: any[] = [
    {
      title: '全部组',
      key: '0',
      expanded: true,
      children: [],
      group: {}
    }
  ];
  currentResourceFilter: string = 'false';

  backList() {
    this.location.back();
  }

  ngOnInit() {
    this.initSearchSchema();
    // this.query(null);
    // this.queryGroup();
  }

  initSearchSchema() {
    let methods: any = [{ label: '全部', value: '' }].concat(RESOURCE_METHOD_ENUM);
    this.searchSchema = {
      properties: {
        resurce: {
          type: 'string',
          title: '资源'
        },
        remark: {
          type: 'string',
          title: '备注'
        },
        method: {
          type: 'string',
          title: '方法',
          default: false,
          enum: methods,
          ui: {
            widget: 'select',
            acl: { ability: ['query'] }
          }
        }
      }
    };
  }

  queryGroup() {
    let tempTree = [
      {
        title: '全部组',
        key: '0',
        expanded: true,
        children: [],
        group: {}
      }
    ];
    this.http.get(`${Api.BaseResourceApi}/group/tree`).subscribe((res: any) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        if (res && res.code === ResponseCode.SUCCESS) {
          if (!res.data || res.data.length < 1) {
            this.groupInfo = tempTree;
            return;
          }
          tempTree[0].children = res.data;
          this.selectedGroups = [];
          if (this.currentGroup && this.currentGroup.id) {
            this.selectedGroups = [this.currentGroup.id];
          }
          this.groupInfo = tempTree;
        } else {
          this.groupInfo = tempTree;
        }
      }
    });
  }

  groupClick(event: NzFormatEmitEvent): void {
    console.log(event);
    this.currentGroup = event.node?.origin['group'];
    const temp: any = [event.node?.origin.key];
    this.selectedGroups = temp;
    this.query(null);
  }

  change(e: STChange) {
    if (e.type === 'pi' || e.type === 'ps') {
      this.params.size = e.ps;
      this.params.current = e.pi;
      this.query(null);
    }
  }

  query(event: any) {
    const current: number = this.params.current || 1;
    const size: number = this.params.size || 10;
    let params: any = {};
    if (event) {
      if (event.resurce) params.resurce = event.resurce;
      if (event.remark) params.remark = event.remark;
      if (event.method) params.method = event.method;
      if (event.deleted !== '') params.deleted = event.deleted;
    }
    if (this.currentGroup && this.currentGroup.id) {
      params.groupId = this.currentGroup.id;
    }
    if (this.currentResourceFilter) {
      params.deleted = this.currentResourceFilter === 'true';
    }
    this.http.get(`${Api.BaseRoleApi}resource/page/${this.role.id}/${current}/${size}`, params).subscribe((res: any) => {
      if (res && res.code === ResponseCode.SUCCESS) {
        if (res.data) this.page = res.data;
      }
    });
  }

  changeResource(item: any, event: any) {
    console.log(item);
    console.log(event);
    if (event === true) {
      this.http.post(`${Api.BaseRoleApi}resource/${this.role.id}`, [item.id]).subscribe((res: any) => {
        if (res && res.code === ResponseCode.SUCCESS) {
          this.msg.success('授权成功');
          this.query(null);
        } else {
          this.msg.error(res ? (res.message ? res.message : '授权失败') : '授权失败');
        }
      });
    } else {
      this.http.delete(`${Api.BaseRoleApi}resource/${this.role.id}`, { resourceId: item.id }).subscribe((res: any) => {
        if (res && res.code === ResponseCode.SUCCESS) {
          this.msg.success('解除成功');
          this.query(null);
        } else {
          this.msg.error(res ? (res.message ? res.message : '解除失败') : '解除失败');
        }
      });
    }
  }
}
